#include "stm32f10x.h"    

int16_t count = 0;

void count_sensor_init(void){
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE); //GPIOB口的
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE); //AFIO中断引脚选择
	GPIO_InitTypeDef type; 
	type.GPIO_Mode = GPIO_Mode_IPD;
	type.GPIO_Pin = GPIO_Pin_11;
	type.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB,&type);
	
	//复位AFIO
	GPIO_AFIODeInit();
	//选择中断引脚
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOB,GPIO_PinSource11);
	//配置exti
	EXTI_DeInit();
	EXTI_InitTypeDef exti;
	exti.EXTI_Line = EXTI_Line11; //配置中断线,选择端口所在的线路
	exti.EXTI_LineCmd = ENABLE; //指定选择线的新状态
	exti.EXTI_Mode = EXTI_Mode_Interrupt; //选择外部中断类型
	exti.EXTI_Trigger = EXTI_Trigger_Rising_Falling; //选择触发类型，上升沿、下降沿触发 还有上下沿都触发
	EXTI_Init(&exti);
	//配置NVIC（内核外设）
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	NVIC_InitTypeDef nvic;
	nvic.NVIC_IRQChannel = EXTI15_10_IRQn;
	nvic.NVIC_IRQChannelCmd = ENABLE;
	nvic.NVIC_IRQChannelPreemptionPriority = 1; //抢占优先级
	nvic.NVIC_IRQChannelSubPriority = 1;//响应优先级
	NVIC_Init(&nvic);
}

//中断函数
void EXTI15_10_IRQHandler(void){
	//先判断中断标志位 看是不是指定的pin触发的
	u8 i = EXTI_GetITStatus(EXTI_Line11);
	if(i != 0){
		count++;
		EXTI_ClearITPendingBit(EXTI_Line11); //清除中断标志位，防止一直申请中断
	}
}

int16_t getCount(void){
	return count;
}

void rotate_sensor_init(void){
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); //GPIOA口的
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE); //AFIO中断引脚选择
	GPIO_InitTypeDef type; 
	type.GPIO_Mode = GPIO_Mode_IPD;
	type.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
	type.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB,&type);
	
	//复位AFIO
	GPIO_AFIODeInit();
	//选择中断引脚
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOA,GPIO_PinSource6);
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOA,GPIO_PinSource7);
	//配置exti
	EXTI_DeInit();
	EXTI_InitTypeDef exti;
	exti.EXTI_Line = EXTI_Line6 | EXTI_Line7; //配置中断线,选择端口所在的线路
	exti.EXTI_LineCmd = ENABLE; //指定选择线的新状态
	exti.EXTI_Mode = EXTI_Mode_Interrupt; //选择外部中断类型
	exti.EXTI_Trigger = EXTI_Trigger_Falling; //选择触发类型，上升沿、下降沿触发 还有上下沿都触发
	EXTI_Init(&exti);
	//配置NVIC（内核外设）
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	NVIC_InitTypeDef nvic;
	nvic.NVIC_IRQChannel = EXTI9_5_IRQn;
	nvic.NVIC_IRQChannelCmd = ENABLE;
	nvic.NVIC_IRQChannelPreemptionPriority = 1; //抢占优先级
	nvic.NVIC_IRQChannelSubPriority = 1;//响应优先级
	NVIC_Init(&nvic);
}
	

void EXTI9_5_IRQHandler(void){
	if(EXTI_GetITStatus(EXTI_Line6) == SET){ //A口
		if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_7) == 0){
			count--;
		}
		EXTI_ClearITPendingBit(EXTI_Line6);
	}else if(EXTI_GetITStatus(EXTI_Line7) == SET){ //C口
		if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_6) == 0){
			count++;
		}
		EXTI_ClearITPendingBit(EXTI_Line7);
	}
}
